/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.Annotation;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.VirtualMachineConf;
import it.polimi.games.epkb.entityClasses.DataFile;
import it.polimi.games.epkb.entityClasses.Component;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class AnnotationJpaController implements Serializable {

    public AnnotationJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

    public AnnotationJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Annotation annotation) throws PreexistingEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            VirtualMachineConf idVirtualMachineConf = annotation.getIdVirtualMachineConf();
            if (idVirtualMachineConf != null) {
                idVirtualMachineConf = em.getReference(idVirtualMachineConf.getClass(), idVirtualMachineConf.getId());
                annotation.setIdVirtualMachineConf(idVirtualMachineConf);
            }
            DataFile idDataFile = annotation.getIdDataFile();
            if (idDataFile != null) {
                idDataFile = em.getReference(idDataFile.getClass(), idDataFile.getId());
                annotation.setIdDataFile(idDataFile);
            }
            Component idComponent = annotation.getIdComponent();
            if (idComponent != null) {
                idComponent = em.getReference(idComponent.getClass(), idComponent.getId());
                annotation.setIdComponent(idComponent);
            }
            em.persist(annotation);
            if (idVirtualMachineConf != null) {
                idVirtualMachineConf.getAnnotationCollection().add(annotation);
                idVirtualMachineConf = em.merge(idVirtualMachineConf);
            }
            if (idDataFile != null) {
                idDataFile.getAnnotationCollection().add(annotation);
                idDataFile = em.merge(idDataFile);
            }
            if (idComponent != null) {
                idComponent.getAnnotationCollection().add(annotation);
                idComponent = em.merge(idComponent);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findAnnotation(annotation.getId()) != null) {
                throw new PreexistingEntityException("Annotation " + annotation + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Annotation annotation) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Annotation persistentAnnotation = em.find(Annotation.class, annotation.getId());
            VirtualMachineConf idVirtualMachineConfOld = persistentAnnotation.getIdVirtualMachineConf();
            VirtualMachineConf idVirtualMachineConfNew = annotation.getIdVirtualMachineConf();
            DataFile idDataFileOld = persistentAnnotation.getIdDataFile();
            DataFile idDataFileNew = annotation.getIdDataFile();
            Component idComponentOld = persistentAnnotation.getIdComponent();
            Component idComponentNew = annotation.getIdComponent();
            if (idVirtualMachineConfNew != null) {
                idVirtualMachineConfNew = em.getReference(idVirtualMachineConfNew.getClass(), idVirtualMachineConfNew.getId());
                annotation.setIdVirtualMachineConf(idVirtualMachineConfNew);
            }
            if (idDataFileNew != null) {
                idDataFileNew = em.getReference(idDataFileNew.getClass(), idDataFileNew.getId());
                annotation.setIdDataFile(idDataFileNew);
            }
            if (idComponentNew != null) {
                idComponentNew = em.getReference(idComponentNew.getClass(), idComponentNew.getId());
                annotation.setIdComponent(idComponentNew);
            }
            annotation = em.merge(annotation);
            if (idVirtualMachineConfOld != null && !idVirtualMachineConfOld.equals(idVirtualMachineConfNew)) {
                idVirtualMachineConfOld.getAnnotationCollection().remove(annotation);
                idVirtualMachineConfOld = em.merge(idVirtualMachineConfOld);
            }
            if (idVirtualMachineConfNew != null && !idVirtualMachineConfNew.equals(idVirtualMachineConfOld)) {
                idVirtualMachineConfNew.getAnnotationCollection().add(annotation);
                idVirtualMachineConfNew = em.merge(idVirtualMachineConfNew);
            }
            if (idDataFileOld != null && !idDataFileOld.equals(idDataFileNew)) {
                idDataFileOld.getAnnotationCollection().remove(annotation);
                idDataFileOld = em.merge(idDataFileOld);
            }
            if (idDataFileNew != null && !idDataFileNew.equals(idDataFileOld)) {
                idDataFileNew.getAnnotationCollection().add(annotation);
                idDataFileNew = em.merge(idDataFileNew);
            }
            if (idComponentOld != null && !idComponentOld.equals(idComponentNew)) {
                idComponentOld.getAnnotationCollection().remove(annotation);
                idComponentOld = em.merge(idComponentOld);
            }
            if (idComponentNew != null && !idComponentNew.equals(idComponentOld)) {
                idComponentNew.getAnnotationCollection().add(annotation);
                idComponentNew = em.merge(idComponentNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = annotation.getId();
                if (findAnnotation(id) == null) {
                    throw new NonexistentEntityException("The annotation with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Annotation annotation;
            try {
                annotation = em.getReference(Annotation.class, id);
                annotation.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The annotation with id " + id + " no longer exists.", enfe);
            }
            VirtualMachineConf idVirtualMachineConf = annotation.getIdVirtualMachineConf();
            if (idVirtualMachineConf != null) {
                idVirtualMachineConf.getAnnotationCollection().remove(annotation);
                idVirtualMachineConf = em.merge(idVirtualMachineConf);
            }
            DataFile idDataFile = annotation.getIdDataFile();
            if (idDataFile != null) {
                idDataFile.getAnnotationCollection().remove(annotation);
                idDataFile = em.merge(idDataFile);
            }
            Component idComponent = annotation.getIdComponent();
            if (idComponent != null) {
                idComponent.getAnnotationCollection().remove(annotation);
                idComponent = em.merge(idComponent);
            }
            em.remove(annotation);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Annotation> findAnnotationEntities() {
        return findAnnotationEntities(true, -1, -1);
    }

    public List<Annotation> findAnnotationEntities(int maxResults, int firstResult) {
        return findAnnotationEntities(false, maxResults, firstResult);
    }

    private List<Annotation> findAnnotationEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Annotation.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Annotation findAnnotation(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Annotation.class, id);
        } finally {
            em.close();
        }
    }

    public int getAnnotationCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Annotation> rt = cq.from(Annotation.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
